package com.twotiger.and.activity.account.coupon;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.HomeActivity;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.adapter.DealCouponAdapter;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.Coupon;
import com.twotiger.and.bean.DataList;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.ListUtils;
import com.twotiger.and.util.PreferencesUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.TimeUtils;
import com.twotiger.and.util.ViewUtils;
import com.view.pulltorefresh.MyListView;
import com.view.pulltorefresh.PullToRefreshBase;
import com.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.view.pulltorefresh.PullToRefreshMyListView;

/**
 * 
 * @Description: 
 * 优惠券 
 * @Author douxy
 * @Date 2015年8月12日 下午1:58:05
 */
@SuppressLint("ResourceAsColor")
public class Couponpage extends BaseActivity implements OnClickListener {

    private PullToRefreshMyListView deal_coupon_refresh_list;
    private View no_content_rl;
    private static final String TAG_refresh = "DealCouponPage_TAG_refresh";

    private static final String UNUSE = "unUse";
    private static final String USED = "used";
    private static final String EXPIRED = "expired";

    private final int GETCOUPONSUCCED = 0;
    private final int GETCOUPONFAIL = 1;
    protected static final int EXCHANGECOUPONSUCCES = 2;
    protected static final int EXCHANGECOUPONFAIL = 3;
    private static final int COUPON_ON_SELECTED = 4;

    private String type = UNUSE;
    private int pNum = 1;
    private ArrayList<Coupon> coupons;
    private RadioGroup coupon_radiogroup;
    private RadioButton timeout_btn;
    private RadioButton notuse_btn;
    private DealCouponAdapter dealCouponAdapter;
    private HashMap<String, String> parms;

    private RadioButton used_btn;
    private SubTitle subTitle;
    private ImageView iv_no_content;
    
    private View header_view; //头布局
    private TextView tv_desc, tv_header_amount;

    @SuppressLint("InflateParams")
    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.deal_coupon_layout, null);
        header_view = inflater.inflate(R.layout.coupon_list_header, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        deal_coupon_refresh_list = (PullToRefreshMyListView) view.findViewById(R.id.deal_coupon_refresh_list);
        no_content_rl = (View) view.findViewById(R.id.coupon_no_content_rl);
        iv_no_content = (ImageView) view.findViewById(R.id.iv_no_content);
        coupon_radiogroup = (RadioGroup) view.findViewById(R.id.coupon_radiogroup);
        notuse_btn = (RadioButton) view.findViewById(R.id.notuse_btn);
        used_btn = (RadioButton) view.findViewById(R.id.used_btn);
        timeout_btn = (RadioButton) view.findViewById(R.id.timeout_btn);
        
        initIdOfHeader();
        addHeaderForList();
        
        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {
            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        subTitle.setTitle("优惠券");
        subTitle.hideBtns();
        subTitle.title_left_bt.setVisibility(View.VISIBLE);
    }

    private void addHeaderForList() {
        ListView lv = deal_coupon_refresh_list.getRefreshableView();
        lv.addHeaderView(header_view);
    }

    private void initIdOfHeader() {
        tv_desc = (TextView) header_view.findViewById(R.id.tv_desc);
        tv_header_amount = (TextView) header_view.findViewById(R.id.tv_header_amount);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.coupon_no_content_rl:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            getcouponlist();
            break;
        default:
            break;
        }
    }

    /** 
     */
    @SuppressLint("HandlerLeak")
    @Override
    protected void setListener() {
        handler = new BaseHandler(this) {
            private AlertDialog showCustomDialog;

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETCOUPONSUCCED:
                    DataList dataList = JSON.parseObject((String) msg.obj, DataList.class);
                    if (dataList.isOk()) {
                        fillDataOfHeader(dataList);
                        List<Coupon> list = JSON.parseArray(dataList.getList(), Coupon.class);
                        if (!ListUtils.isEmpty(list)) {
                            no_content_rl.setVisibility(View.GONE);
                            deal_coupon_refresh_list.setVisibility(View.VISIBLE);
                            if (pNum == 1) {
                                dealCouponAdapter.resetData((ArrayList<Coupon>) list);
                            } else {
                                dealCouponAdapter.addData((ArrayList<Coupon>) list);
                            }
                            dealCouponAdapter.notifyDataSetChanged();
                        } else {
                          //请求数据是空的
                            if(pNum == 1){
                                no_content_rl.setVisibility(View.VISIBLE);
                                deal_coupon_refresh_list.setVisibility(View.GONE);
                                iv_no_content.setImageResource(R.drawable.no_content);
                            }else{
                                showToast("没有更多数据");
                                dealCouponAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                    break;
                case GETCOUPONFAIL:
                    no_content_rl.setVisibility(View.VISIBLE);
                    deal_coupon_refresh_list.setVisibility(View.GONE);
                    break;
                case COUPON_ON_SELECTED:
                    Coupon coupon = dealCouponAdapter.getSelected();
                    if (coupon.getAwardType() == 0 || coupon.getAwardType() == 5) {  //0 现金、1加息卷、4代金券 5、免审红包
                        parms.clear();
                        parms.put("caId", coupon.getCaId());
                        parms.put("token", getToken());
                        getDate(parms, Constants.coupon_exchange, handler, EXCHANGECOUPONSUCCES, EXCHANGECOUPONFAIL, true, false, false);
                    } else {  // 到投资列表页面去         
//                        Intent intent = new Intent(Couponpage.this, HomeActivity.class);
//                        intent.putExtra("BUTTON", R.id.radio_btn2);
//                        startNewActivity(intent, R.anim.slide_left_in, R.anim.slide_left_out, true);
                        startNewActivity(new Intent(Couponpage.this, HomeActivity.class).putExtra(
                            "BUTTON", R.id.radio_btn2), R.anim.push_left_in, R.anim.push_left_out, true);
                    }
                    break;
                case EXCHANGECOUPONSUCCES:
                    Basebean baseBean = JSON.parseObject((String) msg.obj, Basebean.class);
                    if(baseBean.isOk()){
                        
                        PromptManager.showConfirmAlertCommon(Couponpage.this, 0, "兑换成功", "", "确定", "", false, new ReChargeClickListener() {
                            
                            @Override
                            public void onClickConfirm() {
                                pNum = 1;
                                getcouponlist();
                            }
                            
                            @Override
                            public void onClickCancel() {
                                
                            }
                        });
                    }else {
                        showToast(baseBean.codeDesc);
                    }
                    break;
                case EXCHANGECOUPONFAIL:
                    showToast("网络异常");
                    break;
                default:
                    break;
                }
                deal_coupon_refresh_list.onRefreshComplete();
                super.handleMessage(msg);
            }

        };

        deal_coupon_refresh_list.setOnRefreshListener(new OnRefreshListener2<MyListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<MyListView> refreshView) {
                /**
                * 刷新数据
                */
                pNum = 1;
                String refresh_time = PreferencesUtils.getString(getContext(), TAG_refresh, TimeUtils.getFormatDate("yyyy-MM-dd HH:mm"));
                PreferencesUtils.putString(getContext(), TAG_refresh, TimeUtils.getFormatDate("yyyy-MM-dd HH:mm"));
                getcouponlist();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<MyListView> refreshView) {
                /**
                * 加载更多数据
                */
                pNum++;
                getcouponlist();
            }
        });

        coupon_radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                ViewUtils.onCheckedChanged(getApplicationContext(), group, checkedId);
                pNum = 1;
                coupons.clear();
                switch (checkedId) {
                case R.id.notuse_btn://未使用
                    type = UNUSE;
                    break;
                case R.id.used_btn://已使用
                    type = USED;
                    break;
                case R.id.timeout_btn://已过期
                    type = EXPIRED;
                    break;
                default:
                    break;
                }
                getcouponlist();

            }
        });

        no_content_rl.setOnClickListener(this);
    }

    protected void fillDataOfHeader(DataList dataList) {
        if(UNUSE.equals(type)){
            tv_desc.setText("未使用金额:");
            tv_header_amount.setText(ArithUtils.coverMoneyComma(dataList.getNoUseValue()));
        }else if(USED.equals(type)){
            tv_desc.setText("已使用金额:");
            tv_header_amount.setText(ArithUtils.coverMoneyComma(dataList.getUsedValue()));
        }else if(EXPIRED.equals(type)){
            tv_desc.setText("已过期金额:");
            tv_header_amount.setText(ArithUtils.coverMoneyComma(dataList.getExpiredValue()));
        }
    }

    private void getcouponlist() {
        parms.clear();
        parms.put("token", getToken());
        parms.put("pageNum", String.valueOf(pNum));
        parms.put("pageSize", Constants.pageSize);
        parms.put("type", type);
        parms.put("timestamp", TimeUtils.getTimeStamp());
        getDate(parms, Constants.getcouponslist, handler, GETCOUPONSUCCED, GETCOUPONFAIL, true, true, false);
    }

    @Override
    protected void processLogic() {
        parms = new HashMap<String, String>();
        deal_coupon_refresh_list.setMode(PullToRefreshBase.Mode.BOTH);
        initData();

    }

    public void initData() {
        coupons = new ArrayList<Coupon>();
        dealCouponAdapter = new DealCouponAdapter(Couponpage.this, coupons, handler, COUPON_ON_SELECTED);
        deal_coupon_refresh_list.setAdapter(dealCouponAdapter);
        getcouponlist();
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

}
